package com.hooker.penetration

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hooker.adapter.SimpleAdapter
import com.hooker.bean.PackageInfo
import com.hooker.mail.MailInfo
import com.hooker.mail.SendMailUtil
import com.hooker.settings.Setting
import com.hooker.view.MailDialog
import com.sdk.hooker.penetration.R


class MainActivity : AppCompatActivity() {

    var recyclerView: RecyclerView? = null
    lateinit var adapter: SimpleAdapter
    lateinit var emptyView: TextView
    var list: MutableList<PackageInfo> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        initData()
//        sendEmail()
//        testSensor()
        testInstallTime()
        testHooker();
    }

    private fun testInstallTime() {
        val curTime = System.currentTimeMillis()
        val sub = 12 * 60 * 60 * 1000L
        var count = 0


        var results = mutableListOf<Long>()
        var packages = packageManager.getInstalledPackages(0);
        for (packageInfo in packages) {
            if ((packageInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) == 0) {
                results.add(packageInfo.lastUpdateTime)
                if (curTime - packageInfo.lastUpdateTime!! <= sub) {
                    count++
                    Log.d("MainActivity", "packageName======${packageInfo.packageName}")
                }
            }
        }

        Log.d("MainActivity", "count======$count")
    }

    private fun testHooker() {
        var _cls = Class.forName("android.os.SystemProperties");

        var _get = _cls.getMethod("get", String::class.java);
        try {
            var result = _get.invoke(null, "ro.secure") as String
            Log.d("MainActivity", "0".equals(result).toString())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun testSensor() {

        var sensorManager: SensorManager = this
            .getSystemService(Context.SENSOR_SERVICE) as SensorManager
        var sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
        print("senor is null=" + (sensor == null))

        notHasProximitySensor()
    }

    private fun notHasProximitySensor(): Boolean {
        val sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY)
        if (null == sensor) {
            return true
        } else {
            var name = sensor.name
            var vendor = sensor.vendor
            if (TextUtils.isEmpty(name) || TextUtils.isEmpty(vendor)) {
                return true
            } else {
                name = name.toLowerCase()
                vendor = name.toLowerCase()
                if (name.contains("genymotion") || name.contains("goldfish")
                    || vendor.contains("genymobile") || vendor.contains("the android open source project")
                ) {
                    return true
                }
            }
        }
        return false
    }

    private fun sendEmail() {
        var info: MailInfo = MailInfo.Builder()
            .setContent("测试内容")
            .setSubject("测试主题")
            .setToAddress(mutableSetOf("yongdong.lu@jkohjkng.top"))
            .build()
        SendMailUtil.send(info)
    }

    private fun initView() {
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView?.overScrollMode = View.OVER_SCROLL_NEVER
        emptyView = findViewById(R.id.empty)
    }

    private fun initData() {
        getDataFromLocal()
        adapter = SimpleAdapter(this, list, recyclerView!!)
        adapter.setOnItemClickListener(object : SimpleAdapter.OnItemClickListener {
            override fun onClick(view: View, position: Int) {
                adapter.notifyDataSetChanged()
            }
        })
        recyclerView?.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        recyclerView?.adapter = adapter
    }

    /**
     * 获取hook名
     */
    private fun getDataFromLocal() {
        list.clear()
        var set: Set<String> = Setting.getHookApps(this)
        var iterator = set.iterator()
        while (iterator.hasNext()) {
            var name = iterator.next()
            try {
                var info = packageManager.getPackageInfo(name, PackageManager.GET_META_DATA)
                var pg =
                    PackageInfo(info?.packageName, info?.applicationInfo?.loadIcon(packageManager))
                list.add(pg)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            //setting_item:
            R.id.add_rule_item -> {
                var intent = Intent(this@MainActivity, AddRuleActivity::class.java)
                startActivity(intent)
            }
            R.id.rule_list_item -> {
                var intent = Intent(this@MainActivity, RuleListActivity::class.java)
                startActivity(intent)
            }
            R.id.add_mail_item -> {
                var dialog = MailDialog(this)
                dialog.show()
            }

        }
        return true
    }
}
